<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="action"
      :show-file-list="showFileList"
      :headers="header"
      :multiple="multiple"
      :data="data"
      :name="name"
      :with-credentials="withCredentials"
      :drag="drag"
      :accept="accept"
      :disabled="disabled"
      :auto-upload="autoUpload"
      :list-type="listType"

      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-progress="onProgress"
      :on-change="onChange"
      :on-error="onError"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader .el-upload-dragger{
    width: 300px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
</style>

<script>
import { getToken } from 'utils/auth'

export default {
  props: {
    imageUrl: {
      default: null
    },
    multiple: {
      default: false
    },
    data: {},
    name: {},
    withCredentials: {
      default: false
    },
    showFileList: {
      default: false
    },
    drag: {
      default: true
    },
    strategy: {
      default: 'avatar'
    },
    accept: {},
    disabled: false,
    autoUpload: true,
    listType: 'text'
  },
  data() {
    return {
      header: {
        Authorization: `Bearer ${getToken()}`
      },
      action: `${process.env.BASE_API}/api/files/upload?strategy=${this.strategy}`
    }
  },
  methods: {
    handleAvatarSuccess(res, file, success) {
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log(res, file, success)
      this.$emit('on-success', res, file)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    onPreview(file) {
      this.$emit('on-preview', file)
    },
    onRemove(file, fileList) {
      this.$emit('on-remove', file, fileList)
    },
    onProgress(event, file, fileList) {
      this.$emit('on-progress', event, file, fileList)
    },
    onChange(file, fileList) {
      this.$emit('on-change', file, fileList)
    },
    onError(err, file, fileList) {
      this.$emit('onError', err, file, fileList)
    }
  }
}
</script>
